package me.linczh.framework.persiste;

import java.util.Calendar;
import java.util.Date;

import me.linczh.bank.bean.AccountBean;
import me.linczh.bank.bean.EmployeeBean;

public class IdGenerator {
	private static int MAX_COUNT_SIZE = 10000;
	private static int START_POINT = 1000;
	private static Integer ACCOUNT_ID = 1000;
	private static Integer EMPLOYEE_ID = 1000;
	
	public static void initAccountId(Integer id) {
		ACCOUNT_ID = id;
	}
	
	public static void initEmployeeId(Integer id) {
		EMPLOYEE_ID = id;
	}
	
	public static Integer getAccountId() {
		return ACCOUNT_ID;
	}
	
	public static Integer getEmployeeId() {
		return EMPLOYEE_ID;
	}
	
	public static synchronized String nextId(Object bean) {
		if (bean instanceof AccountBean) {
			StringBuffer buffer = new StringBuffer();
			AccountBean account = (AccountBean)bean;
			Calendar c = Calendar.getInstance();
			c.setTime(account.getCreatetime());
			buffer.append(account.getAccounttype().ordinal())
				  .append('-')
				  .append(account.getDeposittype().ordinal())
				  .append('-')
				  .append(String.format("%04d", c.get(Calendar.YEAR)))
				  .append(String.format("%02d", c.get(Calendar.MONTH) + 1))
				  .append(String.format("%02d", c.get(Calendar.DATE)))
				  .append('-')
				  .append(String.format("%04d", ACCOUNT_ID));
			ACCOUNT_ID++;
			if (ACCOUNT_ID == MAX_COUNT_SIZE) ACCOUNT_ID = START_POINT;
			return buffer.toString();
		} else if (bean instanceof EmployeeBean) {
			StringBuffer buffer = new StringBuffer();
			EmployeeBean employee = (EmployeeBean)bean;
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			buffer.append(employee.getPosition().ordinal())
				  .append('-')
				  .append(String.format("%04d", c.get(Calendar.YEAR)))
				  .append(String.format("%02d", c.get(Calendar.MONTH) + 1))
				  .append(String.format("%02d", c.get(Calendar.DATE)))
				  .append('-')
				  .append(String.format("%04d", EMPLOYEE_ID));
			EMPLOYEE_ID++;
			if (EMPLOYEE_ID == MAX_COUNT_SIZE) EMPLOYEE_ID = START_POINT;
			return buffer.toString();
		}
		return null;
	}
}
